package com.avengers.common.lock;

import com.avengers.core.kit.TimeKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author yu.wang
 * @since 4/21/22 11:27 AM
 **/
public class AvengersReentrantLock extends ReentrantLock {
    private static final Logger defaultLogger = LoggerFactory.getLogger(AvengersReentrantLock.class);
    private String id;
    /**
     * 获取锁时间过长阈值
     */
    private static final long THRESHOLD = 500;

    public AvengersReentrantLock() {
        super();
    }

    public AvengersReentrantLock(boolean fair) {
        super(fair);
    }

    public AvengersReentrantLock(String id) {
        super();
        this.id = id;
    }

    public AvengersReentrantLock(String id, boolean fair) {
        super(fair);
        this.id = id;
    }

    @Override
    public void lock() {
        this.lock(defaultLogger);
    }

    public void lock(Logger logger) {
        long startNanoTime = System.nanoTime();
        if (!super.tryLock()) {
            Thread owner = getOwner();
            logger.info("Id_{} get lock from [{}] fail wait {}", id, null == owner ? "-" : owner.getName(), this.getQueueLength());
            super.lock();
        }
        long useMillis = TimeKit.useTimeMillisecond(startNanoTime).longValue();
        logger.info("Id_{} get lock times_{} use {}ms{}", id, getHoldCount(), useMillis, useMillis > THRESHOLD ? " more than " + THRESHOLD + "ms" : "");
    }
}
